package com.web.music.portal.mvc;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.web.music.model.Album;

public class AlbumFormValidator implements Validator {

	public boolean supports(Class givenClass) {
		return givenClass.equals(Album.class);
	}

	public void validate(Object obj, Errors errors) {
		Album album = (Album) obj;
		if (album == null) {
			errors.reject("error.nullpointer", "Null data received");
		} else {
			
			if (album.getTitle().equals("")) {
				errors.rejectValue("title", "error.empty", "Title is required!");
			}
			if (!album.getYear().equals("")) {
				try {
					int year = Integer.parseInt(album.getYear());
					if (year < 0) {
						throw new NumberFormatException();
					}
				} catch (NumberFormatException e) {
					errors.rejectValue("year", "error.empty", "Album year must be positive integer");
				}
			}
		}
	}

}
